package com.chat.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.chat.business.common.thread_local.UserIdThreadLocal;
import com.chat.business.service.IMessageChannelMappingService;
import com.chat.business.service.ISyncService;
import com.chat.common.common.constant.RedisKeyConstant;
import com.chat.common.vo.GroupVO;
import com.chat.common.vo.R;
import com.chat.common.vo.SyncUserDataVO;
import com.chat.common.vo.UserVo;
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author wei kunJie
 * @date 2024/5/9 13:39:46
 */
@Service
public class SyncServiceImpl implements ISyncService {
    @Resource
    private IMessageChannelMappingService messageChannelMappingService;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private RedisTemplate<String, Object> redisTemplateString;

    @Override
    public R<SyncUserDataVO> sync() {
        //查找好友信息
        List<UserVo> userVoList = messageChannelMappingService.getAllFriends().getData();
        //查找群信息
        List<GroupVO> userGroups = messageChannelMappingService.getUserGroups(UserIdThreadLocal.get()).getData();
        List<GroupVO> groupVOList = null;
        if (userGroups != null) {
            //查找群成员
            groupVOList = userGroups
                    .stream().map(groupVO -> {
                        List<UserVo> userVos = messageChannelMappingService.getGroupMembers(groupVO.getId()).getData();
                        if (userVos != null && userVos.size() != 0) {
                            GroupVO groupVO1 = new GroupVO();
                            BeanUtil.copyProperties(groupVO, groupVO1);
                            groupVO1.setUserVoList(userVos);
                            return groupVO1;
                        }
                        return groupVO;
                    }).collect(Collectors.toList());
        }
        //删除redis中群成员缓存
        RLock lock = redissonClient.getLock("Lock:" + RedisKeyConstant.USER_GROUP_CACHE + UserIdThreadLocal.get());
        lock.lock(5, TimeUnit.SECONDS);//加锁，阻塞式等待 5s，默认加的锁都是30s
        redisTemplate.delete(RedisKeyConstant.USER_GROUP_CACHE + UserIdThreadLocal.get());
        lock.unlock();//删除完成，释放锁
        return R.succeed(SyncUserDataVO.builder()
                .userVoList(userVoList)
                .groupVOList(groupVOList)
                .build());
    }
}
